import totalGoodsList from "./goods.js";
export function getGoodsList(params) {
	return new Promise((resolve, reject) => {
		setTimeout(() => {
			const res = {
				code: 200,
				data: {
					list: [],
					totalCount: 0,
					totalPage: 0
				},
				msg: '请求数据成功'
			}
			// 首先判断params.keyword
			let newList = params.keyword ? totalGoodsList.filter(el => el.goodName.includes(params.keyword)) :
				totalGoodsList
				
			//然后进行分页处理
			if ((params.page && typeof params.page === 'number') || (params.limit && typeof params.limit === 'number')) {
				for (let i = (params.page - 1) * params.limit; i < params.page * params.limit; i++) {
					if (i >= newList.length) break
					res.data.list.push(newList[i])
				}
				res.data.totalCount = newList.length
				res.data.totalPage = Math.ceil(newList.length/params.limit)
			} else {
				res.code = 203
				delete res.data
				res.msg = 'page/limit参数错误'
			}
			resolve(res)
		}, 1000)
	})
}

// 搜索商品
export function apiGoods(pageNum, pageSize, keyword) {
	return new Promise((resolute, reject)=>{
		//延时一秒,模拟联网
		setTimeout(()=> {
			try{
				let data = {
					list: [], // 数据列表
					totalCount: 0, // 总数量
					totalPage: 0, // 总页数
					hasNext: false // 是否有下一页
				}
				
				// 符合关键词的记录
				let keywordList = [];
				if (!keyword || keyword == "全部") {
					// 搜索全部商品
					keywordList = totalGoodsList;
				}else{
					// 关键词搜索
					if(keyword=="母婴") keyword="婴"; // 为这个关键词展示多几条数据
					for (let i = 0; i < totalGoodsList.length; i++) {
						let good = totalGoodsList[i]
						if (good.goodName.indexOf(keyword) !== -1) {
							keywordList.push(good)
						}
					}
				}
				
				// 分页
				for (let i = (pageNum - 1) * pageSize; i < pageNum * pageSize; i++) {
					if (i >= keywordList.length) break
					data.list.push(keywordList[i])
				}
				
				// 汇总数据
				data.totalCount = keywordList.length;
				data.totalPage = Math.ceil(data.totalCount/pageSize);
				data.hasNext = pageNum < data.totalPage
				
				//模拟接口请求成功
				console.log("pageNum=" + pageNum + ", pageSize=" + pageSize + ", data.list.length=" + data.list.length + ", totalCount=" + data.totalCount + ", totalPage=" + data.totalPage + ", hasNext=" + data.hasNext + (keyword ? ", keyword=" + keyword : ""));
				resolute(data);
			} catch (e) {
				//模拟接口请求失败
				reject(e);
			}
		},1000)
	})
}
